<?php

namespace App\Api\Three\ShopA;

/**
 * https://docs.qq.com/doc/DRUlEamNJWFFhVmVR
 */

use App\Api\ChannelApi;
use Monolog\Logger;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cache;

// use function GuzzleHttp\json_decode;
//  哈尔滨电信接口
class HarbinTelecom extends ChannelApi
{
    protected $model;
    protected $appKey = '';
    protected $url = '';
    protected $secret = '';
    protected $channel = '';
    protected $config = [];
    protected $HTTPOK = 1; //检查接口返回的数据 返回1 代表返回正确
    protected $root;
    protected $log;
    protected $isTrue = true;
    protected $return_message = '';
    protected $accessToken;
    protected $pname;
    protected $appId;
    protected $appSecret;
    protected $salt;
    protected $salesId;

    public function __construct($url = '', $str = '')
    {
        // 南沙
        $this->pname = 'HarbinTelecom';
        $this->log = new Logger('HarbinTelecom');
        $this->log->pushHandler(
            (new RotatingFileHandler(storage_path('/logs/HarbinTelecom.log'), 14, Logger::DEBUG, true, 0777))->setFormatter(new LineFormatter(null, null, true, true))
        );
        $params = strToKeyValArr($str);
        $this->url = $url;
        $this->appId = $params['appId'];
        $this->appSecret = $params['appSecret'];
        $this->salt = $params['salt'];
    }
    public function sentPost($method, $data)
    {
        // $data = [
        //     'access_token' => $this->accessToken,
        //     'content' => $data,
        //     'method' => ((string)$method),
        //     'version' => (string)"1.0"
        // ];
        // var_dump($data);
        $time = time();
        $headers = [
            'Content-Type:application/json',
            'appId:' . $this->appId,
            'timeStamp:'.$time,
            'sign:' . $this->getSign($data, $time)
        ];
        if ($method != '/token') {
            // $headers[] = 'token:' . $this->getToken();
        }
        $url = $this->url . $method;

        $res = $this->sendBefare($url, $data, $headers);
        return $res;
    }
    public function getToken()
    {
        $token = Cache::get('harbin_telecom_token_catch_qiaoqiao');
        // var_dump($token,555555555);
        if (!empty($token)) {
            $tokenArr = explode('_', $token);
            if (!empty($tokenArr[0]) && $tokenArr[0] >= (time() - 10)) {
                return $tokenArr[1] . (!empty($tokenArr[2]) ? '_' . $tokenArr[2] : '');
            }
        }
        $method = '/token';
        $data = [
            'appId' => $this->appId,
            'appSecret' => $this->appSecret,
        ];
        $res = $this->sentPost($method, $data);
        if (!empty($res)) {
            $res = json_decode($res, true);
            if (isset($res['code']) && $res['code'] == 0) {
                $times = 2 * 60 * 60;
                $str = (time() + $times) . '_' . $res['data'];
                Cache::forever('harbin_telecom_token_catch_qiaoqiao', $str);
                return $res['data'];
            }
        }
        return '';
    }
    public function selectNumber($array = [])
    {
    }
    public function checkOrder($array = [])
    {
        return $this->returnMsg(200, '效验成功');
    }
    public  function getStatusCode($status, $arrsy = [])
    {
    }
    // 提交上游
    public function orderSubmit($array = [])
    {
        // // 暂时先不发送 返回成功
        // return $this->returnMsg(101, !empty($res['msg']) ? $res['msg'] : '提交上游失败', ['msg' => !empty($res['msg']) ? $res['msg'] : '提交上游失败']);
        // 组装提交数据
        $method = '/orderBooking';
        $time = date('Y-m-d H:i:s');
        $this->setData($array);
        if (empty($this->salesId)) {
            return $this->returnMsg(101, '请联系管理员添加销售品', ['msg' => '请联系管理员添加销售品']);
        }
        $address = $this->harbinTelecomAdress($array['post_province'], $array['post_city'], $array['post_area']);
        if (empty($address['code']) || $address['code'] != 200) {
            return $address;
        }
        $ownAddrss = $address['data'];
        $data = [
            'id' => $array['ordersno'],
            'cust_name' => $this->getAesKey($array['pay_name']),
            'cust_id' => $this->getAesKey($array['pay_identity']),
            'phone' => $this->getAesKey($array['pay_phone']),
            'province' => $ownAddrss['province'],
            'provinceCode' => $ownAddrss['province_code'],
            'city' => $ownAddrss['city'],
            'cityCode' => $ownAddrss['city_code'],
            'county' => $ownAddrss['area'],
            'countyCode' => $ownAddrss['area_code'],
            'address' => $array['post_address'],
            'cps' => $array['channel_code'],
            'salesId' => $this->salesId,
            'channel_id' => '2301022488082',   //  渠道编码
            'channel_name' => '道里区乔乔通信电渠',  // 渠道名称
        ];
        $res = $this->sentPost($method, $data);
        // var_dump($res);
        if (is_string($res)) {
            $res = json_decode($res, true);
        }
        if (isset($res['code']) && $res['code'] == '200') {
            return $this->returnMsg(200, !empty($result['msg']) ? $result['msg'] : '下单成功', ['msg' => !empty($result['msg']) ? $result['msg'] : '下单成功']);
        }
        return $this->returnMsg(101, !empty($res['msg']) ? $res['msg'] : '提交上游失败', ['msg' => !empty($res['msg']) ? $res['msg'] : '提交上游失败']);
        if (!empty($res)) {
            return $this->returnMsg(200, '提交成功', ['order_id' => !empty($res) ? $res : '']);
        }
        return $this->returnMsg(100, '提交失败', ['order_id' => !empty($res) ? $res : '']);
    }
    // 不同套餐 设置的参数不一样
    public function setData($data)
    {
        switch ($data['channel_code']) {
            case 'lmk.cps.ybhllxcardwhyxhlwzbhebqqxxkjyxgs29_2022.152888098_Y23010288647':
                $this->salesId = '00000000D45ACE0F98E84E7DE053AA1410ACC9B5';
                break;
            case 'lmk.cps.ybhllxcardwhyxhlwzbhebqqxxkjyxgs39_2022.152888098_Y23010288647':
                $this->salesId = '00000000DA7A1BFFB4BB22F6E053AC1410AC30DD';
                break;
            case 'lmk.cps.ybhlnuanxincardwhyxhlwzbhebqqxxkjyxgs39.152888098_Y23010288647':
                $this->salesId = '00000000F21D1A0D34C366A9E053AC1410ACDCDB';
                break;
        }
        return '';
    }
    // 查询订单 查询
    public function queryOrderStatus($array = [])
    {
        $method = '/orderSelect';
        $data = [
            'orderNo' => $array['ordersno'],
            'beginTime' => !empty($array['created_at']) ? date('Y-m-d', strtotime('-1 day', $array['created_at'])) : date('Y-m-d', strtotime('-1 day')),
            'endTime' => date('Y-m-d', strtotime('+1 day')),
        ];
        // var_dump($data);
        $res = $this->sentPost($method, $data);
        return json_decode($res, true);
    }
    // 处理数据 将数据处理成统一格式
    public function queryOneOrder($array = [])
    {
        $res = $this->queryOrderStatus($array);
        if (empty($res['data'])) {
            return $this->returnMsg(100, '数据为空');
        }
        // var_dump($res);
        $getData = $res['data'][0];
        $statusDatas = [
            0 => '提交中',
            1 => '提交上游',
            // 2 => '拒收单',
            10 => '审核中',
            11 => '待发货',
            20 => '已发货',
            30 => '已签收',
            40 => '已激活',
            50 => '异常单',
            51 => '取消单',
            60 => '失败单'
        ];
        $returnStatusArr = array(
            '待发货' => 11,
            '已发货待激活' => 20,
            '已激活' => 40,
            '超时未激活' => 51,
            '激活失败' => 50,
            '激活失败' => 50,
            '实名制失败' => 50
        );
        $data = [
            'id' => $getData['orderno'],
            'sup_order' => $getData['orderno'],
            'created_at' => date('Y-m-d H:i:s', strtotime($getData['stime'])),
            'order_desc' => !empty($getData['deliveryTime']) ? $getData['deliveryTime'] : '',
            'order_desc_at' => !empty($getData['deliveryTime']) ? date('Y-m-d H:i:s', strtotime($getData['deliveryTime'])) : '',
            'order_num' => $getData['orderno'],
            'express_company' => '京东',
            'express_number' => !empty($getData['oddNumber']) ? $getData['oddNumber'] : '',
            'iccid' => !empty($getData['iccid']) ? $getData['iccid'] : '',
            'province' => !empty($getData['province']) ? $getData['province'] : '',
            'city' => !empty($getData['city']) ? $getData['city'] : '',
            'address' => !empty($getData['address']) ? $getData['address'] : '',
            'status' => !empty($returnStatusArr[$getData['states']]) ? $returnStatusArr[$getData['states']] : '',
            'card_status_desc' => !empty($getData['states']) ? $getData['states'] : ''
        ];
        return $this->returnMsg(200, '查询成功', [$data]);
    }
    public function sendBefare($url, $data, $headers)
    {
        ksort($data);
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => json_encode($data, JSON_UNESCAPED_UNICODE),
            CURLOPT_HTTPHEADER => $headers,
        ));

        $response = curl_exec($curl);
        $this->log->info('哈尔滨电信参数:' . json_encode($data) . 'header参数:' . json_encode($headers) . '返回参数:' . $response);
        curl_close($curl);
        return $response;
    }
    public function sendBefare_back($url, $data, $headers, $isPost = 1)
    {
        // return 1212222222222;
        $curl = curl_init(); // 启动一个CURL会话
        if (!empty($isPost)) {
            // $url = $url . '?' . http_build_query($data);
        }
        var_dump($url, 666666666);
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在
        // curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        if ($isPost == 1) {
            curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
            curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data)); // Post提交的数据包 http_build_query
        }
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        if (!empty($headers)) {
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        }

        $result = curl_exec($curl); // 执行操作
        if (curl_error($curl)) {
            //请求失败，返回错误信息
            $res =  curl_error($curl);
            var_dump($res);
            return $res;
        }
        curl_close($curl); // 关闭CURL会话
        $this->log->info('湖南电信参数:' . json_encode($data) . '返回参数:' . $result);
        return $result;
    }
    public function sendBefareGet($url, $data, $headers)
    {
        $curl = curl_init(); // 启动一个CURL会话
        $url = $url . '?data=' . urlencode($data);
        // var_dump($url, 666666666);
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在
        // curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        if (!empty($headers)) {
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        }

        $result = curl_exec($curl); // 执行操作
        // var_dump($result, 111111111);
        curl_close($curl); // 关闭CURL会话
        return $result;
    }
    public function getSign($params, $time)
    {
        ksort($params);
        $str = json_encode($params, JSON_UNESCAPED_UNICODE);
        // $b = $str . '&appId=' . $this->appId . '&timeStamp=' . $time . '&salt=' . $this->salt;
        $b = $str .$this->appSecret;
        return md5($b);
    }
    public function getSign_back($str)
    {
        if (is_array($str)) {
            $str = json_encode($str, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        }
        $strs = strtolower(md5($str));
        $getPKey = $this->getPublicKey();
        $key = openssl_pkey_get_public($getPKey);
        $return = openssl_public_encrypt($strs, $crypted, $key);
        if (!$return) {
            return '';
        }
        return base64_encode($crypted);
    }
    public function getAesKey($str)
    {
        $key = 'K_admin_040506_k';
        // $key = bin2hex($key);
        $str = openssl_encrypt($str, 'AES-128-ECB', $key, 1);
        return strtoupper(bin2hex($str));
    }
    public function harbinTelecomAdress($province, $city, $area)
    {
        if (empty($province) || empty($city) || empty($area)) {
            return $this->returnMsg(100, '未查询到归属地', ['msg' => '归属地传递不能为空']);
        }

        // $province = str_replace('壮族自治区', '', $province);
        // $province = str_replace('自治区', '', $province);
        // $province = str_replace('省', '', $province);
        // $province = str_replace('市', '', $province);
        // $city = str_replace('市', '', $city);
        // $city = str_replace('区', '', $city);
        // $city = str_replace('县', '', $city);
        if (mb_strlen($province) > 2) {
            $province = mb_substr($province, 0, mb_strlen($province) - 1);
        }
        if (mb_strlen($city) > 2) {
            $city = mb_substr($city, 0, mb_strlen($city) - 1);
        }
        if (mb_strlen($area) > 2) {
            $area = mb_substr($area, 0, mb_strlen($area) - 1);
        }
        $res = DB::table('harbin_telecom_address')->where('province', 'like', '%' . $province . '%')->where('city', 'like', '%' . $city . '%')->where('area', 'like', '%' . $area . '%')->first();
        if (!$res) {
            return $this->returnMsg(100, '未查询到归属地', ['msg' => '未查询到归属地']);
        }
        return $this->returnMsg(200, '查询成功', ['province' => $res->province, 'city' => $res->city, 'city_code' => $res->city_code, 'province_code' => $res->province_code, 'area_code' => $res->area_code, 'area' => $res->area]);
    }
}
